package com.yjs.app.trade.web.controller.sys;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yjs.app.trade.core.util.JedisUtil;
import com.yjs.app.trade.core.util.PropertiesUtils;
import com.yjs.app.trade.core.util.StringUtils;
import com.yjs.app.trade.entity.base.SysConstant;
import com.yjs.app.trade.service.service.business.member.MemberService;
import com.yjs.app.trade.service.service.sys.UserAuthorityService;
import com.yjs.app.trade.service.service.sys.UserService;
import com.yjs.app.trade.web.controller.base.BaseController;
import com.yjs.app.trade.web.controller.base.util.Result;
import com.yjs.app.trade.web.controller.interceptor.AuthenticationUtil;

import net.sf.json.JSONObject;

@Controller
@RequestMapping(value = "/sys/authority")
public class UserAuthorityController extends BaseController {
	
	public static String superviseUrl = PropertiesUtils.getProperty("supervise.index.url");

	@Autowired
	UserAuthorityService userAuthorityService;
	
	@Autowired
	UserService userService;
	
	@Autowired
	MemberService memberService;
	
	/**
	 * app用户登录
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/appLogin", method = RequestMethod.POST)
	@ResponseBody
	public String appLogin(String data) {
		if (StringUtils.isBlank(data)) {
			return Result.cfail(SysConstant.ErrorCode.NO_LOGIN,"用户名或密码错误");
		}
		JSONObject jsonObject = dpackData(data);
		String username = jsonObject.getString("username");
		String password = jsonObject.getString("password");
		String mac = jsonObject.getString("mac");
		Map<String, Object> map = new HashMap<String, Object>();
		String token = userAuthorityService.appLogin(username, password, loginKey);
		if (token != null && JedisUtil.get(baseToken + token) != null) {
			logger.debug(JedisUtil.get(baseToken + token));
			List<JSONObject> typesInfo = JSONObject.fromObject(JedisUtil.get(baseToken + token)).getJSONArray("appNatures");
			List<String> types = new ArrayList<String>();
			for (JSONObject json : typesInfo) {
				String type = json.getString("appNatureId");
				types.add(type);
				if(StringUtils.equals("MANAGER", type)){
					map.put("superviseIndexUrl",superviseUrl);
				}
			}
			Map<String, Integer> autMap =  AuthenticationUtil.getUserAuts(types, JSONObject.fromObject(JedisUtil.get(baseToken + token)).getJSONArray("userPermissionId"));
			boolean isAut = false;
			for(Map.Entry<String, Integer> entry : autMap.entrySet()) {
				if (entry.getValue() == 1) {
					isAut = true;
				}
			}
			if (!isAut) {
				return Result.cfail(SysConstant.ErrorCode.CODE_ERROR,"没有权限登录");
			}
			String passportId = JSONObject.fromObject(JSONObject.fromObject(JedisUtil.get(baseToken + token)).get("allAttribute")).getString("PASSPORT_ID");
			if (StringUtils.strIsNotNull(jsonObject.get("jpushId"))) {
				Map<String,Object> param = new HashMap<>();
					param.put("mac", jsonObject.getString("mac"));
					param.put("jpushId", jsonObject.getString("jpushId"));
					List<String> oldUserId = userService.getUserId(param);
				if (oldUserId.size() >= 1) {
					for (String string : oldUserId) {
						param.clear();
						param.put("passportId", string);
						param.put("jpushId", "");
						userService.updateUserInfo(param);
					}
				}
				param.clear();
				param.put("passportId", passportId);
				param.put("jpushId", jsonObject.getString("jpushId"));
				userService.updateUserInfo(param);
			}
			map.put(userToken, baseToken + token);
			Map<String, Object> user = userService.getUserInfo(passportId);
			/*
			if (user.get("identification") != null && Integer.parseInt(user.get("identification").toString()) == 1) {
				map.put("identification", true);
			} else {
				map.put("identification", false);
			}*/
			map.put("identification", true);
			if (user.get("mac") != null && mac.equals(user.get("mac").toString())) {
				map.put("mac", true);
			} else {
				map.put("mac", false);
				if (user.get("mobile") != null) {
					String mobile =  user.get("mobile").toString();
					map.put("mobile", mobile.replace(mobile.substring(3, 7), "****"));
				}
			}
			map.put("ROLE", autMap);
			map.put("isExpire", memberService.findMemberAppVSIsExpire(JSONObject.fromObject(JSONObject.fromObject(JedisUtil.get(baseToken + token)).get("allAttribute")).getString("MEMBER_ID")));
		} else {
			return Result.cfail(SysConstant.ErrorCode.CODE_ERROR,"用户名或密码错误");
		}
		return Result.csuccess(map);
	}
	
	
	
	/*
	private String getAutPermissionIdByMemberType (String memberType) {
		if (StringUtils.equals("BUYER", memberType)) {
			return "PERMISSION_12000001";
		} else if (StringUtils.equals("SELLER", memberType)) {
			return "PERMISSION_12100001";
		} else if (StringUtils.equals("DISPATCH", memberType)) {
			return "PERMISSION_12200001";
		}
		return "";
	}*/
	
	
	
	/**
	 * app用户修改密码
	 * @return
	 */
	@RequestMapping(value = "/updatePwd", method = RequestMethod.GET)
	@ResponseBody
	public Object updatePwd(String data, HttpServletRequest request) {
		JSONObject jsonObject = dpackData(data);
		/*String mobile="";
		if (jsonObject != null && jsonObject.get("mobile") != null) {
			mobile = jsonObject.getString("mobile");
		} else {
			mobile = userService.getUserInfo(getUserId(request)).get("mobile").toString();
		}*/
		/*if (JedisUtil.get(mobileCodeRedisHead + mobile) != null) {
			authCode = JSONObject.fromObject(JedisUtil.get(mobileCodeRedisHead + mobile)).getString("code");
		} else {
			return Result.cfail(SysConstant.ErrorCode.CODE_ERROR, "验证码已经过期!");
		}*/
		//if (StringUtils.equals(authCode, jsonObject.get("authCode").toString())) {
		String loginName = jsonObject.get("username") != null ? jsonObject.getString("username") : JSONObject.fromObject(getUserInfo(request).get("allAttribute")).getString("PASSPORT_NAME");
		try {
			userAuthorityService.updatePwd(loginName, jsonObject.getString("oldPwd"), jsonObject.getString("newPwd"), "APPUPDATEPASSWORD",loginKey);
			return Result.csuccess(); 
		} catch (Exception e) {
			return Result.cfail(SysConstant.ErrorCode.CODE_ERROR, "原密码错误，修改失败");
		}
		//}
		//return Result.cfail(SysConstant.ErrorCode.CODE_ERROR, "验证码错误！");
	}
	
	/**
	 * app用户登录
	 * @return
	 */
	@RequestMapping(value = "/testLogin", method = RequestMethod.GET)
	@ResponseBody
	public String appLoginTest(String username, String password) {
		String token = userAuthorityService.appLogin(username, password, loginKey);
//		System.out.println(JedisUtil.get(baseToken + token));
		return baseToken + token;
	}
	
	/**
	 * 测试专用
	 * @return
	 */
	@RequestMapping(value = "/appLogint", method = RequestMethod.GET)
	@ResponseBody
	public String loginTest() {
		return "0af6668c894691598d6ee21e8d99d1b927bd434fa35efea5185eed70ac304989ff93962bda8e30b5d4fe3b96db7f8d56b06278b1ba56060786804966548dd687a45eea6c26aa3a2694e2765b37f21de597f885b5877f95c2f25c0a5e5591065ae9ea8e2c10de189bc97974c5afbd4ae526e32fa34edf033f2635133b732fb1edf72b80d3a473d5ca4b250282bbc0cd83643b5e88dd6bb852b273a00e35b0a1abad9a5639a42d4326014810935aefca90a35d66e5d37d528dc5243f77e608bacefc20c03fb5adeac51d0579fa51b4f28dc0b003a6cbcd60cd2719a5190bec85ae";
	}
}
